// pages/indexDefault/index.js
const app = getApp();
const utils = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMore: 1,
    title: '',
    navBarHeight: 60,
    autoplays: true,
    interval: 3500,
    duration: 1000,
    myCardId: 0,
    keyword: '',
    tagindex: 1,
    staffList: [],
    latitude: 0,
    longitude: 0,
    hasJJK: false,
    mobile: '',
    spikeList: [],//爆品秒杀
    packPid: 0,//玖玖卡套餐pid
    regionType: 1,
    cityId: 0,
    sorttype: 1,//0 综合, 1 距离, 2 折扣, 3 促销折扣
    industryId: 0,
    classList: [],
    regionIds:'',
    layer: 0
  },

  staffListener(e) {
    this.data.keyword = e.detail,
    this.data.CurrentPage = 1;
    this.getStaffListByDistance(this.data.cityId);
  },

  changeSort: function (e) {
    let sort = e.currentTarget.dataset.sort;
    this.data.regionType = 1;
    this.setData({
      sorttype: sort,
      CurrentPage: 1,
      staffList: []
    })
    this.getStaffListByDistance(this.data.cityId);
  },

  getMyCard: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.myUserInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            let staffid = res.data.Data.Id;     
            that.setData({
              myCardId: staffid
            })
          }
        }
      },
    })
  },

  toMyJJK: function () {
    wx.reLaunch({
      url: '/pages/index/index?id=' + this.data.myCardId + '&isPlatform=1',
    })
  },

  toCuxiaoDetail: function (e) {
    let cardId = e.currentTarget.dataset.cardid;
    wx.navigateTo({
      url: '../promotionDetail/index?cardId=' + cardId,
    })
  },

  tapClassSelect: function (e) {
    let cid = e.currentTarget.dataset.cid;
    this.setData({
      industryId: cid,
      CurrentPage: 1,
      staffList: []
    })
    this.getStaffListByDistance(this.data.cityId);
  },

  toCardDetail: function (e) {
    let id = e.currentTarget.dataset.id;
     wx.reLaunch({
        url: '/pages/index/index?id=' + id + '&isPlatform=1',
      })
  },

  changeTagindex: function (e) {
    let index = e.currentTarget.dataset.index;
    this.data.regionType = 1;
    this.setData({
      tagindex: index,
      CurrentPage: 1,
      staffList: []
    })
    if (index == 3) {
      // this.getCardProduct();
    } else {
      this.getStaffListByDistance(this.data.cityId);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    if(e.regionId){
      this.data.cityId = e.regionId;
      this.data.layer = e.layer;
    }
    this.getLocation();
  },

  getStaffListByDistance: function (cityId) {
    let that = this;
    let sorttype = that.data.sorttype;
    let range = 2;
    if (that.data.tagindex == 4) {
      range = 3;
      sorttype = 0;
    }

    let data= {
      cardItemId: 0,
      range: range,
      storeAppId: app.globalData.storeAppId,
      lat: that.data.latitude,
      lng: that.data.longitude,
      keyword: that.data.keyword,
      page: that.data.CurrentPage,
      cityType: that.data.regionType, //1当前市的数据2其他市的数据
      sortType: sorttype,
      industryId: that.data.industryId,
      regionIds: cityId,
      layer: that.data.layer,
      bossState: -1   //此处用来表示平台首页是否显示： 0 不显示, 1 平台显示
    }

    wx.showLoading({title: '加载中...',mask: true})
    wx.request({
      url: app.globalData.host + '/api/staff/GetListBySale',
      data: data,
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        if(res.data.Code != 0){
          utils.showModal(res.data.Message);         
          return;
        }      

        let cardId = that.data.myCardId;
        let staffList = res.data.Data.Items;
        for (let i = 0; i < staffList.length; i++) {
          staffList[i].Avater = utils.formatAvater(staffList[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
          staffList[i].Discount = 100 - staffList[i].UseDiscount;
          staffList[i].ShowDiscount = staffList[i].Discount / 10;
          staffList[i].Distance = parseFloat(staffList[i].Distance).toFixed(2);
          staffList[i].Distances = parseFloat(staffList[i].Distance / 1000).toFixed(2);
        }
        if (that.data.CurrentPage != 1) {
          let preList = that.data.staffList;
          staffList = preList.concat(staffList);
        } 
        that.setData({
          staffList: staffList,
          loadingMore: res.data.Data.TotalPages
        })
      },
    })
  },

  // 获取地理位置
  getLocation: function () {
    let that = this;
    utils.getLocation((location)=>{
     that.data.latitude = location.lat;
     that.data.longitude = location.lng;
     that.getCurrentCity(location.lat, location.lng);
    },app);   
  },
  getCurrentCity: function (lat, log) {
    let that = this;
    that.data.regionType = 1;
    that.getStaffListByDistance(that.data.cityId);    
    wx.request({
      url: app.globalData.host + '/api/Tool/GetRegionByGeo?lat=' + lat + '&lng=' + log,
      success: function (res) {
        let title = '';        
        if (res.data.Code == 0) {          
          // that.data.cityId = res.data.Data.CityId;
          title =  res.data.Data.CityName.length<=4 ? res.data.Data.CityName : res.data.Data.CityName.substr(0,3) + '...';
        }
        that.setData({
          title: title
        })
      }
    })
  },  

  //设置图片自适应
  getImgInfoHeight: function (list) {
    var that = this;
    var heightArr = [];
    var f = 0;
    for (let h = 0; h < list.length; h++) {
      wx.getImageInfo({
        src: list[h].ShowImg,
        success: function (res) {
          list[h].width = res.width;
          list[h].height = res.height;
        },
        complete: function (res) {
          f++;
          if (f == list.length) {
            for (let g = 0; g < list.length; g++) {
              //获取图片真实宽度  
              var imgwidth = list[g].width,
                imgheight = list[g].height,
                //宽高比  
                ratio = imgwidth / imgheight;
              //计算的高度值  
              var viewHeight = 690 / ratio;
              var vieheight = viewHeight;
              heightArr.push(vieheight);
              list[g].imgheight = vieheight;
            }
            for (let t = 0; t < list.length; t++) {
              var maxN = that.checkMax(heightArr);
              list[t].maxHeight = maxN;
            }
            that.setData({
              adverList: list
            })
          }
        }
      })
    }
  },
  //判断最大值
  checkMax: function (heightArr) {
    var maxN = Math.max.apply(null, heightArr);
    return maxN;
  },

  // 加载更多
  loadMore: function () {
    let that = this;
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getStaffListByDistance(that.data.cityId);
    } else {
      return
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (app.globalData.userInfo) {
      that.getMyCard();
    } else {
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  //编辑页面
  toEdit: function(e){
     let uid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: '/pages/h5page/index?url=' + encodeURIComponent(app.globalData.webhost + 'setdisplay.html?uid=' +  uid),
    })
  },
  onReachBottom: function () {
    if (this.data.tagindex == 1 || this.data.tagindex == 4) {
      this.loadMore();
    }
  }
})